<template>
  <div>
    <Breadcrumb :title="subTitle" :opt-data="roomOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="roomData"
          :custom-empty="true"
          @pageChanged="getRoomData"
          @sizeChanged="getRoomData"
          @filterChange="getRoomData">
          <div slot="customOpts">
            <div>
              <el-tooltip :open-delay="300" content="导入房间配置" placement="top">
                <el-upload action="action" :before-upload="uploadRoomConfig"
                           class="display-inline-block mar-lft-5">
                  <el-button class=" table-filter-opt-btn ">
                    <i class="iconfont icon-bendidaoru font-size-16"></i>
                  </el-button>
                </el-upload>
              </el-tooltip>
            </div>
          </div>
          <EmptyContent slot="empty" :opt-data="roomOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog v-loading="roomFormLoading" :visible.sync="showRoomConfigDialog" :append-to-body="true"  :close-on-click-modal="false"
                 :title="isEditRoomConfig ? '修改房间配置' : '新增房间配置'" width="750px" top="100px">
        <el-form :ref="roomConfigFormRef" :model="roomConfigForm" :rules="roomConfigFormRules" size="medium"
                 label-width="80px">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="房间名称" prop="roomName">
                <el-input v-model="roomConfigForm.roomName" placeholder="请填写房间名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间类别" prop="roomType">
                <el-select v-model="roomConfigForm.roomType" :filterable="true" :clearable="true"
                           placeholder="请选择房间类别" size="small" class="width-100">
                  <el-option v-for="project in roomTypeArray" :key="project.value" :label="project.label"
                             :value="project.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">

            <el-col :span="12">
              <el-form-item label="平板类型" prop="padType">
                <el-select v-model="roomConfigForm.padType" placeholder="请选择平板类型"
                           size="small"
                           class="width-100" clearable>
                  <el-option v-for="(item,index) in padTypeArray" :label="item.label" :value="item.value"
                             :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!roomConfigForm.padModelId && isEditRoomConfig">
              <el-form-item label="平板型号">
                <el-input v-model="roomConfigForm.device" placeholder="请填写平板型号" class="width-100">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-else>
              <el-form-item label="平板型号">
                <el-select v-model="roomConfigForm.padModelId" placeholder="请选择平板型号" size="small"
                           class="width-100" clearable filterable @change="selectPad">
                  <el-option v-for="(item,index) in ipadConfig"
                             :label="`${item.label}-(${item.window.width}*${item.window.height})`" :value="item.value"
                             :key="index">
                    <span>{{item.label}}</span>
                    <span class="mar-lft font-color-warning">({{item.window.width}}*{{item.window.height}})</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" v-if="!roomConfigForm.padModelId && isEditRoomConfig">
            <el-col :span="12">
              <el-form-item label="页面宽度">
                <el-input-number v-model="roomConfigForm.window.width" controls-position="right"
                                 class="width-100">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="页面高度">
                <el-input-number v-model="roomConfigForm.window.height" controls-position="right"
                                 class="width-100">
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="房间模版">
                <el-select v-model="roomConfigForm.templateId" placeholder="请选择房间模版" size="small"
                           class="width-100" :disabled="isEditRoomConfig" clearable @change="changeTemplateId">
                  <el-option v-for="(item,index) in templateList" :label="item.label" :value="item.value"
                             :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分控版本" prop="ezControlVersion">
                <el-input v-model="roomConfigForm.ezControlVersion" placeholder="请填写分控版本"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="环境控制">
                <el-select v-model="roomConfigForm.isEnvControl" placeholder="是否含有环境控制页面" size="small"
                           class="width-100">
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="高级编程">
                <el-select v-model="roomConfigForm.isAdvancedProgram" placeholder="是否含有高级编程" size="small"
                           class="width-100">
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="isEditRoomConfig" label="版本号">
            <el-input v-model="roomConfigForm.version" placeholder="请填写版本号"></el-input>
          </el-form-item>
          <el-form-item label="主题色">
            <ThemePicker v-model="roomConfigForm.theme"></ThemePicker>
          </el-form-item>
          <el-form-item v-if="isEditRoomConfig" label="预览图">
            <ImageUpload :preview-type="previewType.room" :image-list="roomConfigForm.previewImages"></ImageUpload>
          </el-form-item>
          <el-form-item prop="remarks" label="备注">
            <el-input v-model="roomConfigForm.remarks" type="textarea" placeholder="请填写备注"></el-input>
          </el-form-item>
          <div class="mar-top text-align-right">
            <el-button type="info" @click="showRoomConfigDialog = false">取消</el-button>
            <el-button type="primary" @click="roomConfigFormSubmit">提交</el-button>
          </div>
        </el-form>
      </el-dialog>
      <el-dialog
        title="分享"
        :visible.sync="showShareDialog"
        :close-on-click-modal="false"
        width="500px">
        <el-select class="width-100" v-model="shareUserIds" filterable multiple collapse-tags
                   placeholder="请选择要分享用户">
          <el-option
            v-for="item in userData"
            :key="item._id"
            :label="item.name + ' - ' + item.username"
            :value="item._id">
          </el-option>
        </el-select>
        <div class="mar-top text-align-right">
          <el-button type="info" @click="showShareDialog = false">取消</el-button>
          <el-button type="primary" @click="shareRoomConfigSubmit">提交</el-button>
        </div>
      </el-dialog>
      <!--删除项目需要验证-->
      <el-dialog
        title="删除房间"
        :visible.sync="deleteRoomDialog"
        :close-on-click-modal="false"
        width="500px"
        center>
        <p>即将删除该房间，请确认是否删除？</p>
        <el-form
          :ref="delRoomFormRef"
          :model="delRoomForm"
          :rules="delRoomFormRules"
          size="small"
        >
          <el-form-item prop="date">
            <el-input v-model="delRoomForm.date" placeholder="默认当前日期-格式如2024/01/01"></el-input>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="delRoomFormCancel">取消</el-button>
              <el-button size="medium" type="primary" @click="delRoomFormSubmitted">确定</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {
    deepCopy,
    deepCopyWithJson,
    downloadFileApi,
    editorConfigPreview, formatHttpParams,
    generateUID,
    getUserInfo,
    JSONParse,
    messageHandle
  } from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import roomTableCfg from "../../../config/table/room";
  import EZTable from '../../../components/table/EZTable.vue';
  import {routerMeta} from "@/router/routerMeta";
  import {
    momentFormat,
    roomTypeArray,
    uploadPreviewType,
    userRoleCfg,
    padTypeArray,
    globalReserveOptions,
	  globalVariableOptions,
    globalGuideOptions
  } from "@/config/common";
  import FileSaver from 'file-saver';
  import ThemePicker from "@/components/IDE/ThemePicker.vue";
  import ImageUpload from '@/components/ImageUpload.vue';
  import {assetBaseUrl} from "@/config/env";
  import API from "@/api";
  import {WidgetFactory} from "@/modules/IDE/widgetFactory";

  export default {
    name: "RoomManagement",
    components: {
      EZTable, ThemePicker, ImageUpload
    },
    data() {
      return {
        userRoleCfg: userRoleCfg,
        userInfo: getUserInfo(),
        previewType: uploadPreviewType,
        tableId: tableIdConfig.room,
        tableLoading: true,
        tableHdl: null,
        roomData: [],
        selectedRoomConfig: {},
        showRoomConfigDialog: false,
        isEditRoomConfig: false,
        roomFormLoading: false,
        roomConfigFormRef: 'roomConfigFormRef',
        roomConfigForm: {
          roomName: "",
          window: {width: 1024, height: 768},
          device: "",
          version: "",
          isAdvancedProgram: '',
          isEnvControl: '',
          roomType: '',
          ezControlVersion: '',
          previewImages: [],
          theme: 'theme1',
          homePageId: '',
          roomScenes: [],
          globalVar: [],
          remarks: '',
          templateId: '',
          padModelId: '',
          padType: ''
        },
        roomConfigFormRules: {
          roomName: [
            {required: true, message: '请填写房间名称', trigger: ['blur', 'change']}
          ],
          roomType: [
            {required: true, message: '请选择房间类别', trigger: ['blur', 'change']}
          ],
          padType: [
            {required: true, message: '请选择平板类型', trigger: ['blur', 'change']}
          ],
        },
        roomTypeArray: roomTypeArray,
        detailConfig: {},
        projectId: '',
        subTitle: '',
        templateList: [],
        ipadConfig: [],
        padTypeArray: padTypeArray,
        showShareDialog: false,
        userData: [],
        shareUserIds: [],
        deleteRoomDialog: false,
        delRoomForm: {
          date: ''
        },
        delRoomFormRef: 'delRoomFormRef',
        delRoomFormRules: {
          date: [
            {required: true, message: '请填写当前日期', trigger: 'blur'}
          ],
        },
        roomId: '',
        sourceRect: {},
        exportParams:{}
      }
    },
    computed: {
      roomOptData() {
        return [
          {
            type: 'btn',
            label: '项目图片管理',
            icon: 'icon-upload',
            callback: () => {
              this.$router.push({name: routerMeta.projectAsset.name, params: {pid: this.projectId}});
            }
          },
          {
            type: 'btn',
            label: '新增房间配置',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.projectId = this.$route.params.pid;
      this.subTitle = this.$route.query.subTitle;
      this.initTableConfig();
      this.initRoomForm();
      this.getRoomData();
      this.getTemplateData();
      this.getAllIpad();//拿平板型号数据
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, roomTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const room = deepCopyWithJson(data);
          this.selectedRoomConfig = room;
          const {
            _id, roomName, roomType, window: padWindow = {}, previewImages = [],
            theme = 'theme1', device, version, ezControlVersion, isEnvControl, isAdvancedProgram,
            homePageId, roomScenes = [], globalVar = [], remarks, templateId = '', padModelId = '', padType = ''
          } = room;
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showRoomConfigDialog = true;
              this.isEditRoomConfig = true;
              this.roomConfigForm = {
                _id: _id,
                roomName: roomName,
                window: {width: padWindow.width, height: padWindow.height},
                device: device,
                version: version,
                isEnvControl: isEnvControl,
                isAdvancedProgram: isAdvancedProgram,
                roomType: roomType,
                ezControlVersion: ezControlVersion,
                previewImages: previewImages,
                theme: theme,
                roomScenes: roomScenes,
                homePageId: homePageId,
                globalVar: globalVar,
                remarks: remarks,
                templateId: templateId,
                padModelId: padModelId,
                padType: padType
              };
              this.sourceRect = deepCopy(room.window)
              break;
            case tableOptBtnConfig.preview.type: {
              //预览
              editorConfigPreview({type: 'room', roomId: _id});
              break;
            }
            case tableOptBtnConfig.select.type:
              //编辑
              window.open(this.$router.resolve({
                name: routerMeta.roomEditor.name,
                params: {projectName: this.subTitle,rid: _id}
              }).href, '_blank');
              break;
            case tableOptBtnConfig.assetManage.type:
              this.$router.push({
                name: routerMeta.roomAsset.name,
                params: {pid: this.projectId, rid: _id},
              });
              break;
            case tableOptBtnConfig.copy.type:
              this.copyRoomConfigSubmit(room)
              break;
            case tableOptBtnConfig.delete.type:
              //  this.deleteRoomConfig(room);
              this.roomId = _id
              this.deleteRoomDialog = true
              break;
            case tableOptBtnConfig.share.type:
              this.shareRoomConfig();
              break;
            case tableOptBtnConfig.export.type:
              this.exportRoomConfig(room);
              break;
            case tableOptBtnConfig.exportZip.type:
              this.exportPage(room);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initRoomForm() {
        this.roomConfigForm = {
          roomName: "",
          window: {width: 1024, height: 768},
          device: "",
          version: "",
          isEnvControl: '',
          isAdvancedProgram: '',
          roomType: '',
          ezControlVersion: '',
          previewImages: [],
          theme: 'theme1',
          homePageId: '',
          roomScenes: [],
          globalVar: [],
          remarks: '',
          templateId: '',
          padModelId: '',
          padType: ''
        };
      },
      exportPage(room) {
        this.$confirm(`是否导出设备元数据(旧版本分控请选择不导出)?`, "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        }).then(() => {
          downloadFileApi(`${assetBaseUrl}/roomConfig/download/config/assets`, {_id: room._id, exportMetadata: true});
        }).catch(() => {
          downloadFileApi(`${assetBaseUrl}/roomConfig/download/config/assets`, {_id: room._id, exportMetadata: false});
        });
      },
      resetRoomForm() {
        this.initRoomForm();
        const roomForm = this.$refs[this.roomConfigFormRef];
        roomForm && roomForm.resetFields();
      },
      getRoomData() {
        this.tableLoading = true;
        const selector = {projectId: this.projectId};
        const tableParam = this.tableHdl.assembleTableParam();
        const transform = (val) => {
          switch (val) {
            case '0':
              return '否';
            case '1':
              return '是';
            default:
              return '-';
          }
        }
        API.room.roomList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.roomData = data.map(room => {
            const {window = {}, isEnvControl, isAdvancedProgram, templateId, padType} = room;
            const templateName = this.templateList.find(type => type.value === templateId) || {};
            const padTypeText = this.padTypeArray.find(type => type.value === padType) || {};
            return {
              ...room,
              size: `<span class="font-color-success">${window.width} x ${window.height}</span>`,
              isEnvControlText: transform(isEnvControl),
              isAdvancedProgramText: transform(isAdvancedProgram),
              templateName: templateName.label,
              roomEditBtn: !room.isShare,
              padTypeText: padTypeText.label
            }
          });
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      getUserData() {
        API.user.userAll().then(result => {
          const {data = []} = result;
          this.userData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      clickCreateBtn() {
        this.resetRoomForm();
        this.isEditRoomConfig = false;
        this.showRoomConfigDialog = true;
      },
      //内置平板协议
      addPadProtocol(roomId){
          const deviceParam={
            deviceTypeId:"qfh9MXTKpC9GPXEhH",
            manufacturerId:"ssz2FA5v6DajRYbmk",
            seriesId:"aAjteYk847YYPCDTY",
            modelId:"Q5mS4igTMyyCsSjif",
            deviceId:"4wWG8eyL2BcMEud3X",
            deviceCode:"25200307",
            protocolId:"CGbDzmdjQyFtsHXXF",
            controlId:"",
            customCommand:[],
            deviceOtherName:"",
            protocols:["CGbDzmdjQyFtsHXXF","TqE7qvw4Rw2qfHwXg","2S8aHfbWSfXnJ672Z","DFfdeedgyeZctX2za"],
            roomId:roomId
          }
          API.roomDevice.roomDeviceAdd([deviceParam]).then(resp => {
          }).catch(err => {
            console.log('err', err);
          });

      },
      roomConfigFormSubmit() {
        this.$refs[this.roomConfigFormRef].validate((valid) => {
          if (!valid) return;
          this.roomFormLoading = true;
          const params = {
            projectId: this.projectId,
            ...this.roomConfigForm,
          };
          //比较页面宽高大小 更改比率
          const {width: tWidth, height: tHeight} = this.sourceRect;
          const {width: sWidth, height: sHeight} = this.roomConfigForm.window;
          if (this.isEditRoomConfig) {
            API.room.roomEdit(params).then((resp) => {
              this.roomFormLoading = false;
              this.showRoomConfigDialog = false;
              this.$message({
                message: "房间配置编辑成功!",
                type: "success",
                duration: 1500,
              });
              this.getRoomData();
              //编辑分辨率大小替换分辨率
              if (sWidth !== tWidth || sHeight !== tHeight) {
                this.getRoomDetail(this.sourceRect, this.roomConfigForm.window,this.roomConfigForm._id)
               setTimeout(()=>{
                 this.saveRoom(this.roomConfigForm._id)
               },2000)
              }
            }).catch((err) => {
              this.roomFormLoading = false;
              console.log("err: ", err);
            });
          } else {
            params.roomScenes = [
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'SystemOn',
                name: '开启系统'
              },
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'SystemOff',
                name: '关闭系统'
              },
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'LocalConference',
                name: '本地会议'
              },
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'VideoConference',
                name: '视频会议'
              },
            ];
	          switch (params.padType) {
		          case 'control':
			          params.globalVar = globalVariableOptions;
			          break;
		          case 'reserve':
			          params.globalVar = globalReserveOptions;
			          break;
		          case 'guidance':
			          params.globalVar = globalGuideOptions;
			          break;
		          default:
			          break;
	          }
            API.room.roomAdd(params).then((resp) => {
              this.roomFormLoading = false;
              this.showRoomConfigDialog = false;
              this.$message({
                message: "房间配置新增成功!",
                type: "success",
                duration: 1500,
              });
              this.getRoomData();
              this.addPadProtocol(resp.data)
              //如果选了房间模版，就要匹配当前选中的分辨率进行替换
              if(params.templateId){
                if (sWidth !== tWidth || sHeight !== tHeight) {
                  this.getRoomDetail(this.sourceRect, this.roomConfigForm.window,resp.data)
                  setTimeout(()=>{
                    this.saveRoom(resp.data)
                  },2000)
                }
              }
            }).catch((err) => {
              this.roomFormLoading = false;
              console.log("err: ", err);
            });
          }
        });
      },
      // 复制
      copyRoomConfigSubmit(row) {
        this.$confirm(`确定要复制【${row.roomName}】的房间吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          const params = {_id: this.selectedRoomConfig._id};
          this.tableLoading = true
          API.room.roomClone(params).then((resp) => {
            this.$message({
              message: "房间配置复制成功!",
              type: "success",
              duration: 1500,
            });
            this.tableLoading = false
            this.getRoomData();
          }).catch((err) => {
            console.log("err: ", err);
            this.tableLoading = false
          });
        }).catch(() => {
        });
      },
      //删除
      deleteRoomConfig(room) {
        this.$confirm(`确定要删除【${room.roomName}】的房间配置吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.tableLoading = true
          API.room.roomDelete({roomId: room._id}).then((resp) => {
            this.$message({
              message: "房间配置删除成功!",
              type: "success",
              duration: 1500,
            });
            this.getRoomData();
            this.tableLoading = false
          }).catch((err) => {
            console.log("err: ", err);
            this.tableLoading = false
          });
        }).catch(() => {
        });
      },
      shareRoomConfig() {
        this.getUserData();
        this.showShareDialog = true;
      },
      shareRoomConfigSubmit() {
        const params = {_id: this.selectedRoomConfig._id, shareUserIds: this.shareUserIds};
        this.tableLoading = true
        this.showShareDialog = false;
        API.room.roomShare(params).then((resp) => {
          this.$message({
            message: "房间配置分享成功!",
            type: "success",
            duration: 1500,
          });
          this.tableLoading = false
          this.getRoomData();
        }).catch((err) => {
          console.log("err: ", err);
          this.tableLoading = false
        });
      },
      //导出房间的资源
      exportRoomConfig(room) {
        this.$confirm(`确定要导出【${room.roomName}】的房间配置吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          API.room.roomExport({roomId: room._id || ''}).then(resp => {
            this.detailConfig = resp.data;
            const {room} = resp.data;
            const {roomName = '房间'} = room;
            FileSaver.saveAs(new Blob([JSON.stringify(this.detailConfig)]), `${roomName}_房间配置.json`);
          }).catch(err => {
          });
        }).catch(() => {
        });
      },
      //导入配置
      uploadRoomConfig(file) {
        let fileReader = new FileReader();
        this.tableLoading = true;
        fileReader.onload = async (e) => {
          try {
            const configs = JSONParse(e.target.result || "{}");
            configs.room.projectId = this.projectId;
            configs.room.isTemplate = false;
            API.room.roomImport(configs).then(() => {
              this.tableLoading = false;
              this.$message({
                message: "导入成功!",
                type: "success",
                duration: 1500,
              });
              this.getRoomData();
            }).catch((err) => {
              this.tableLoading = false;
              console.log("err: ", err);
            });
          } catch (err) {
            console.log(`配置导入失败: ${err.message}`);
            this.tableLoading = false;
          }
        };
        fileReader.readAsText(file);
        return false;
      },
      getTemplateData() {
        API.room.roomTemplateList().then(result => {
          const {data = []} = result;
          this.templateList = data
        }).catch(err => {
          console.log('err', err);
          this.tableLoading = false;
        });
      },
      getAllIpad() {
        API.ipad.ipadAll().then(result => {
          const {data = []} = result;
          this.ipadConfig = data
        }).catch(err => {
          console.log('err', err);
          this.tableLoading = false;
        });
      },
      selectPad(val) {
        const list = this.ipadConfig.find(item => {
          return item.value === val
        })
        this.$set(this.roomConfigForm, 'device', list.label);
        this.$set(this.roomConfigForm, 'window', list.window);
      },
      delRoomFormSubmitted() {
        this.$refs[this.delRoomFormRef].validate((valid) => {
          if (!valid) return;
          let date = moment().format(momentFormat.dateSlant)
          if (this.delRoomForm.date !== date) {
            this.$notify({title: '', message: '验证错误', type: 'error', duration: 3000});
          } else {
            API.room.roomDelete({roomId: this.roomId}).then((resp) => {
              this.$message({
                message: "房间配置删除成功!",
                type: "success",
                duration: 1500,
              });
              this.getRoomData();
              this.tableLoading = false
            }).catch((err) => {
              console.log("err: ", err);
              this.tableLoading = false
            });
            this.deleteRoomDialog = false
          }
          this.$refs[this.delRoomFormRef].resetFields();
        })
      },
      delRoomFormCancel() {
        this.deleteRoomDialog = false
        this.$refs[this.delRoomFormRef].resetFields();
      },
      //导出修改分辨率
      getRoomDetail(sourceRect, targetRect,roomId) {
        API.room.roomDetail({roomId: roomId}).then(resp => {
          const {
            _id = '', projectId = '', roomName = '', window, device = '', version = '', widgets = [], subPages = [],
            roomType = '', theme, globalVar = [], roomScenes = [], remarks = '', previewImages = [], homePageId
          } = resp.data;
          widgets.forEach(widget => {
            WidgetFactory.widgetScaleTransform(widget, sourceRect, targetRect);
          });
          let params;
          params = {
            _id: _id,
            projectId: projectId,
            roomName: roomName,
            window: targetRect,
            device: device,
            roomType: roomType,
            widgets: widgets,
            version: version,
            theme: theme,
            globalVar: globalVar,
            roomScenes: roomScenes,
            remarks: remarks,
            homePageId: homePageId,
            previewImages: previewImages
          };
          this.exportParams.roomParams=params
            // console.log("主页",widgets)
          // 先异步请求所有的子页面数据，然后再组装页面数据
          Promise.all(this.getSubPageData(subPages,roomId)).then((subPageArr = []) => {
            subPageArr.forEach(subPage => {
              const {widgets = []} = subPage;
              widgets.forEach(widget => {
                WidgetFactory.widgetScaleTransform(widget, sourceRect, targetRect);
              });
                // console.log("zi页",widgets)
            });
            this.exportParams.subPages=subPageArr
          }).catch(err => {
          });
        }).catch(err => {
        });
      },
      getSubPageData(subPages = [],roomId) {
        const promiseArr = [];
        subPages.forEach(subPage => {
          promiseArr.push(new Promise((resolve, reject) => {
            const param = {roomId: roomId, subPageId: subPage.id};
            API.room.roomSubPageDetail(param).then(resp => {
              resolve({id: subPage.id, widgets: resp.data});
            }).catch(err => {
              reject(err);
            });
          }));
        });
        return promiseArr;
      },
      saveRoom(roomId) {
        Promise.all(this.saveRoomSubPage(roomId)).then(res => {
          API.room.roomEdit(formatHttpParams(this.exportParams.roomParams)).then(resp => {
          }).catch(err => {
          });
        }).catch(err => {
        });
      },
      saveRoomSubPage(roomId) {
        const promiseArr = [];
        this.exportParams.subPages.forEach(page => {
          const params = {
            roomId: roomId,
            widgets:page.widgets ,
          };
          promiseArr.push(new Promise((resolve, reject) => {
            API.room.roomSubPageEdit(formatHttpParams(params)).then(resp => {
              resolve();
            }).catch(err => {
              reject(err);
            });
          }));
        });
        return promiseArr;
      },
      //修改房间模版
      changeTemplateId(templateId){
        let list=  this.templateList.find(item=> item.value===templateId)
        this.sourceRect=list?list.window:{}
      }
    },
  }
</script>

<style scoped lang="less">

</style>
